/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ufps.cuatro.util;

import java.awt.datatransfer.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTable;
import javax.swing.table.TableModel;

public abstract class ExportTableAsHTML {   
    
    public static String export(TableModel tableModel) { 
        
        JTable tableExport = new JTable(tableModel);
        
        final DataFlavor HTML_STRING_FLAVOR;
        
        try {
            // The datatransfer API could do with some work here...            
            HTML_STRING_FLAVOR = new DataFlavor("text/html;class=java.lang.String");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ExportTableAsHTML.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        } 
        
        // Exports selected data only.
        tableExport.selectAll(); // Evil.
        javax.swing.TransferHandler handler = tableExport.getTransferHandler();
        
        if (handler == null) {
            System.err.println("No transfer handler.");
            return "";
        }
    
        int actions = handler.getSourceActions(tableExport);
        if ((actions & javax.swing.TransferHandler.COPY) == 0) {
            System.err.println("Table does not support copy.");
            return "";
        }

        java.awt.datatransfer.Clipboard clipboard = 
                new java.awt.datatransfer.Clipboard("Export table as HTML private clipboard");
        
        try {
            handler.exportToClipboard(tableExport, clipboard, javax.swing.TransferHandler.COPY);
        } catch (IllegalStateException ex) {
            Logger.getLogger(ExportTableAsHTML.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
        
        java.awt.datatransfer.Transferable transferable = clipboard.getContents(/* unused... */null);
        if (transferable == null) {
            System.err.println("Clipboard empty");
            return "";
        }
        // Just support HTML as String.
        // Could also use HTML as Reader or UTF-8 InputStream
        // (particularly for large tables,
        // if the implementation was better).
        if (!transferable.isDataFlavorSupported(HTML_STRING_FLAVOR)) {
            System.err.println("HTML (String) not supported");
            return "";
        }
        
        try {
            Object data = transferable.getTransferData(HTML_STRING_FLAVOR);
            String html = (String) data;
            int i = html.indexOf("<html>");
            return html.substring(i);
        } catch (java.io.IOException ex) {    
            Logger.getLogger(ExportTableAsHTML.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        } catch (java.awt.datatransfer.UnsupportedFlavorException ex) {
            Logger.getLogger(ExportTableAsHTML.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("HTML (String) not supported");
            return "";
        }
    }
    
    private String stripMatterTag(Object obj){
        return obj.toString().trim().replaceAll("\t"," ").replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("^@TM@","");
    }
   
    /**
     * Verify if the input string is a tabular data string in HTML format.
     * <p>
     * The string should start with <i><html><table></i>
     *
     * @param s The string for verification.
     * @return <i>true</i> if the input string is a tabular data string in
     *          HTML format, <i>false</i> otherwise.
     *
     */
    private boolean isHTMLTableData(String s) {
        boolean found = false;
       
        if (s != null) {
            // Normalize the input string with small case.
            s = s.toLowerCase();
           
            // Now we verify if the data is a tabular data in HTML format.
            Pattern p = Pattern.compile("<html>");
            Matcher m = p.matcher(s);
            found = m.find();
        }
        return found;
    } // End of the method isHTMLTableData()
    
      private String extractData(String s) {
        String data = null;
       
        if (s != null) {
            // Normalize the input string with small case.           
            s = s.toLowerCase();              
            // Verify that the input string is a tabular data string in HTML
            // format
            if (isHTMLTableData(s)) {
//               System.out.println(s);
                // Find numerica data, expressed in percentage.
                Pattern p = Pattern.compile("[0-9]+[\\.]*[0-9]*%") ;
                Matcher m = p.matcher(s);
                if (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    data = s.substring(start, end);
                    return data;
                } // End of if (m.find()) statement
                // Find the string "yes"
                p = Pattern.compile("yes");
                m = p.matcher(s);
                if (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    data = s.substring(start, end);
                    return data;
                } // End of if (m.find()) statement
                // Find the string "no"
                p = Pattern.compile("no");
                m = p.matcher(s);
                if (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    data = s.substring(start, end);
                    return data;
                } // End of if (m.find()) statement
                // Find the string "online"
                p = Pattern.compile("online");
                m = p.matcher(s);
                if (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    data = s.substring(start, end);
                    return data;
                } // End of if (m.find()) statement
                // Find the string "offline"
                p = Pattern.compile("offline");
                m = p.matcher(s);
                if (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    data = s.substring(start, end);
                    return data;
                } // End of if (m.find()) statement
            } // End of if (isHTMLTableData())
        } // End of if (s != null) statement.
        return data;
    } // End of the method extractData
    
//      private void convertToHTML(File f, Table theTable) throws Exception {
//        try {
//            if( f.exists() )
//                f.delete();
//            f.createNewFile();
//            FileWriter fileWriter=new FileWriter(f);
//            String sTitle = theTable.getTableTitle();
//            //fileWriter.write(theTable.getTableTitle()+"\r\n\r\n");
//            int rowCnt=theTable.getTable().getRowCount();
//            int colCnt=theTable.getTable().getColumnCount();
//            fileWriter.write("<html>\r\n");
//            fileWriter.write("<head>\r\n");
//            fileWriter.write("<title>" + sTitle + "</title>\r\n");
//            fileWriter.write("</head>\r\n");
//            fileWriter.write("<body>\r\n");
//            fileWriter.write("<h1><center>" + sTitle + "</center></h1><br><br>\r\n");
//            fileWriter.write("<table border=\"1\" width=\"100%\">\r\n");
//            fileWriter.write("<tr>\r\n");
//            for(int i=0;i<colCnt;i++){
//                //if(i!=0) fileWriter.write("\t");
//                fileWriter.write("<td><center>");
//                fileWriter.write(theTable.getTable().getColumnName(i));
//                fileWriter.write("</center></td>\r\n");
//            }
//            fileWriter.write("</tr>\r\n");
//            //fileWriter.write("\r\n");
//            String colData = null;
//            for(int i=0;i<rowCnt;i++){
//                fileWriter.write("<tr>\r\n");
//                for(int j=0;j<colCnt;j++){
//                    Object dataObj=theTable.getTable().getValueAt(i,j);
//                    if(dataObj!=null) {
//                        colData = stripMatterTag(dataObj);
//                        // Verify if the column data is a tabular data in HTML format. In this case, we only want to extract
//                        // the numerica data expressed in percentage.
//                        if (isHTMLTableData(colData)) {
//                            colData = extractData(colData);
//                        }
//                        if ((colData.length() == 0) || (colData.equals("")))
//                            colData = "&nbsp";
//                        //fileWriter.write(dataObj.toString().trim().replaceAll("\t"," ").replaceAll("\r"," ").replaceAll("\n"," "));
//                    }else{
//                        //fileWriter.write("NULL");
//                        colData = "NULL";
//                    }
//                    fileWriter.write("<td>" + colData + "</td>\r\n");
//                    //if(j!=(colCnt+1)) fileWriter.write("\t");
//                }
//                fileWriter.write("</tr>\r\n");
//                //if(i!=(rowCnt+1)) fileWriter.write("\r\n");
//            }
//            fileWriter.write("</table>\r\n");
//           
//            // Write out the EXTEND if any
//            String extStr = (String)theTable.getCompModel().getModelProp("extend");
//            if (extStr!=null){
//                fileWriter.write("<br>\n");
//                fileWriter.write(extStr);
//            }
//           
//            fileWriter.write("</html>\r\n");
//            fileWriter.close();
//        } catch (Exception e) {
//            throw e;
//        }
//    } // End of the method covertToHTML()
     
    
    
}